<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  useMessage,
  NTag, NFlex, NCard, NAvatar, NSwitch, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import {getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import {forEach} from "lodash-es";
import default_image from "@/assets/images/mz.jpg";

defineOptions({ name: '提交记录' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE


const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '提交记录',
  initForm: {},
  doCreate: api.createExamPost,
  doUpdate: api.updateExamPost,
  doDelete: api.deleteExamPost,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/exams/exam/file',
  routers: [
    {
      name: '',
      type: '',
      num: '',
    },
  ],
})
const deptOption = ref([])
const isDisabled = ref(false)
const onCreate = () => {
  return {
    question: '',
    select1: '',
    score1: '',
    select2: '',
    score2: '',
    select3: '',
    score3: '',
    select4: '',
    score4: '',
  }
}
onMounted(() => {
  $table.value?.handleSearch()
})
async function hanbeSumit() {
  console.log(1, 'modalForm')
}

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入模板称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}


const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'title',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '用户昵称',
    key: 'user_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '测试结果',
    key: 'result_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateExam(row)
    $message?.success(row.state ? '已取消禁' : '已禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false ? true : false
  } finally {
    row.publishing = false
  }
}

//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code == 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="提交记录">
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getExamPost"
        default-expand-all
    >
      <template #queryBar>
        <QueryBarItem label="试卷名称" :label-width="80">
          <NInput
              v-model:value="queryItems.title"
              clearable
              type="text"
              placeholder="请输入试卷名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="会员昵称" :label-width="70">
          <NInput v-model:value="queryItems.user_name" clearable type="text" placeholder="请输入会员姓名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        style="width: 1200px !important"
        @save="handleSave"
    >
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :rules="deptRules"
          @submit="hanbeSumit"
      >
        <NFormItem label="试卷名称" path="title">
          <NInput v-model:value="modalForm.title" clearable placeholder="请输入名称" />
        </NFormItem>

        <NFormItem label="试卷简介" path="desc">
          <NInput style="width: 590px;" type="textarea" v-model:value="modalForm.desc" clearable
                  placeholder="请输入试卷简介" />
        </NFormItem>

      </NForm>
    </CrudModal>
  </CommonPage>
</template>
